#include<stdio.h>
#include<pthread.h>
#include<unistd.h>

int counter=0;   //柜台上是否有饭，0-没有，1-有

//定义互斥锁与条件变量
pthread_mutex_t mutex;
pthread_cond_t cond;

void* Cook(void* arg)
{
  while(1){
    pthread_mutex_lock(&mutex);  //先加锁
    if(counter==1){
      //表示有饭，阻塞厨师
      pthread_cond_wait(&cond,&mutex);
    }
    //没有饭，厨师要去做饭
    usleep(10);
    printf("饭好了，快来吃饭啦！\n");
    counter=1;
    pthread_cond_signal(&cond);  //唤醒至少一个顾客来吃饭
    pthread_mutex_unlock(&mutex);   //解锁
  }
  return NULL;
}
void* Custom(void* arg)
{
  while(1){
    pthread_mutex_lock(&mutex);  //先加锁
    if(counter==0){
      //没有饭，阻塞顾客
      pthread_cond_wait(&cond,&mutex);
    }
     //有饭，顾客吃饭
    usleep(10);
    printf("饭真好吃，再来一碗吧！\n");
    counter=0;
    pthread_cond_signal(&cond);   //唤醒至少一个厨师来做饭
    pthread_mutex_unlock(&mutex);
  }
  return NULL;
}
int main()
{
  //初始化互斥锁，条件变量
  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&cond,NULL);

  //首先创建两个线程--厨师、顾客
  pthread_t cook_tid,cus_tid;
  int ret;
  ret=pthread_create(&cook_tid,NULL,Cook,NULL);
  if(ret!=0){
    perror("pthread_create error!\n");
    return -1;
  }
  
  ret=pthread_create(&cus_tid,NULL,Custom,NULL);
  if(ret!=0){
    perror("pthread_create error!\n");
    return -1;
  }

  //线程等待
  pthread_join(cook_tid,NULL);
  pthread_join(cus_tid,NULL);
  
  //互斥锁、条件变量的销毁
  pthread_mutex_destroy(&mutex);
  pthread_cond_destroy(&cond);
  return 0;
}
